#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QFile>
#include <QDebug>
#include <algorithm>

#include "addcountry.h"
#include "addathlete.h"
#include "updateathlete.h"
#include "updateCountry.h"
#include "country.h"
#include "athlete.h"

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("奥运会信息管理系统");

    database = new db(this, "COUNTRY");

    //读取数据
    readData();
    //初始化UI
    initUI();
    //初始化表1数据
    initData1();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::readData()
{
#if 0
    readCountry();
    readAthlete();
#else
    queryCountry();
#endif
}

void MainWindow::initUI()
{
    //QTableWidget1初始化设置
    QStringList headerList;
    headerList << QString("国家数字代码") << QString("国家字母代码") << QString("国家中文名称") << QString("国家英文名称") << QString("参赛人数")
               << QString("金牌数量") << QString("银牌数量") << QString("铜牌数量");
    ui->tableWidget->setColumnCount(headerList.size());
    ui->tableWidget->setHorizontalHeaderLabels(headerList);
    //QTableWidget2初始化设置
    QStringList headerList1;
    headerList1 << QString("序号") << QString("运动员姓名") << QString("运动员号码") << QString("获奖日期") << QString("奖牌类型")
                << QString("项目名称") << QString("项目成绩") << QString("所属国家");
    ui->tableWidget_2->setColumnCount(headerList1.size());
    ui->tableWidget_2->setHorizontalHeaderLabels(headerList1);
    ui->comboBox->addItem("国家");
    ui->comboBox->addItem("队员");
}

void MainWindow::initData1(QString country_name)
{
    // 删除所有行
    while(ui->tableWidget->rowCount() > 0)
    {
        ui->tableWidget->removeRow(0);
    }


    int numcode;
    QString alphaCode;
    QString chiName;
    QString engName;
    int teamSize = 0;
    int gold = 0;
    int silver = 0;
    int bronze = 0;
    for(int i = 0 ; i < vecCountry.size(); i++)
    {
        vecCountry[i].getValue(numcode, alphaCode, chiName, engName, teamSize, gold, silver, bronze);
        if(country_name.size() == 0 || chiName ==  country_name)
        {
            int nRowCount = ui->tableWidget->rowCount();                          //获取表行数
            ui->tableWidget->insertRow(nRowCount);                                //插入新行

            QTableWidgetItem* item = new QTableWidgetItem(QString::number(numcode));

            QTableWidgetItem* item1 = new QTableWidgetItem(alphaCode);

            QTableWidgetItem* item2 = new QTableWidgetItem(chiName);

            QTableWidgetItem* item3 = new QTableWidgetItem(engName);

            QTableWidgetItem* item4 = new QTableWidgetItem(QString::number(teamSize));

            QTableWidgetItem* item5 = new QTableWidgetItem(QString::number(gold));

            QTableWidgetItem* item6 = new QTableWidgetItem(QString::number(silver));

            QTableWidgetItem* item7 = new QTableWidgetItem(QString::number(bronze));

            ui->tableWidget->setItem(nRowCount, 0, item);
            ui->tableWidget->setItem(nRowCount, 1, item1);
            ui->tableWidget->setItem(nRowCount, 2, item2);
            ui->tableWidget->setItem(nRowCount, 3, item3);
            ui->tableWidget->setItem(nRowCount, 4, item4);
            ui->tableWidget->setItem(nRowCount, 5, item5);
            ui->tableWidget->setItem(nRowCount, 6, item6);
            ui->tableWidget->setItem(nRowCount, 7, item7);
        }

    }

}

void MainWindow::initData2(int type, QString sWhere)
{
    // 删除所有行
    while(ui->tableWidget_2->rowCount() > 0)
    {
        ui->tableWidget_2->removeRow(0);
    }

    int id;
    QString athleteName;
    QString code;
    QString medalDate;
    QString medalLevel;
    QString eventName;
    QString score;
    QString country_name;

    for(int i = 0; i < vecCountry.size(); i++)
    {
        for(int j = 0; j < vecCountry[i].vecAthlete.size(); j++)
        {
            Athlete& sport =  vecCountry[i].vecAthlete[j];
            sport.getValue(id, athleteName, code, medalDate, medalLevel, eventName, score, country_name);
            if(
                (type == 0 && sWhere == country_name ) ||
                (type == 1 && sWhere == athleteName ) ||
                (type == -1)
                )
            {
                int nRowCount = ui->tableWidget_2->rowCount();    //获取表行
                ui->tableWidget_2->insertRow(nRowCount);                                //插入新行
                QTableWidgetItem* item = new QTableWidgetItem(QString::number(id));
                QTableWidgetItem* item1 = new QTableWidgetItem(athleteName);
                QTableWidgetItem* item2 = new QTableWidgetItem(code);
                QTableWidgetItem* item3 = new QTableWidgetItem(medalDate);
                QTableWidgetItem* item4 = new QTableWidgetItem(medalLevel);
                QTableWidgetItem* item5 = new QTableWidgetItem(eventName);
                QTableWidgetItem* item6 = new QTableWidgetItem(score);
                QTableWidgetItem* item7 = new QTableWidgetItem(country_name);
                ui->tableWidget_2->setItem(nRowCount, 0, item);
                ui->tableWidget_2->setItem(nRowCount, 1, item1);
                ui->tableWidget_2->setItem(nRowCount, 2, item2);
                ui->tableWidget_2->setItem(nRowCount, 3, item3);
                ui->tableWidget_2->setItem(nRowCount, 4, item4);
                ui->tableWidget_2->setItem(nRowCount, 5, item5);
                ui->tableWidget_2->setItem(nRowCount, 6, item6);
                ui->tableWidget_2->setItem(nRowCount, 7, item7);
            }
        }


    }

}

void MainWindow::on_pushButton_query_clicked()
{
    QString sQuery = ui->lineEdit->text();

    QString sql;
    if(!sQuery.isEmpty())
    {
        if(ui->comboBox->currentIndex() == 0)//第一个选项是0
        {
            initData1(sQuery);//一开始走的是空的，在选择完后是有值的
            initData2(0, sQuery);//在数据库里面按照country来查询，也可以其他的
        }
        else
        {
            initData2(1, sQuery);
        }
    }
    else
    {
        initData1();
        initData2(3);
    }
}

void MainWindow::on_tableWidget_1_itemClicked(QTableWidgetItem* item)
{
    int nRow = item->row();//获取点的哪一行
    if(nRow < 0)
    {
        return;
    }

    QString chiName  = ui->tableWidget->item(nRow, 2)->text();
    if(chiName.isEmpty())
    {
        return;
    }
    m_chiName = chiName;
    initData2(0, chiName);
}

void MainWindow::on_pushButton_addCountry_clicked()
{
    addCountry dlg;
    if(dlg.exec() == QDialog::Accepted)
    {
        QString alphaCode = dlg.getAlphaCode();
        QString chiName = dlg.getChiName();
        QString engName = dlg.getEngName();
        int teamSize = dlg.getTeamSize().toInt();
        int gold = dlg.getGold().toInt();
        int silver = dlg.getSilver().toInt();
        int bronze = dlg.getBronze().toInt();

        int index = getCountryIndex(chiName);
        if(index >= 0)
        {
            QMessageBox::information(nullptr, "提示", QString("[%1]已存在，请勿重复添加！").arg(chiName));
            return;
        }
        Country country;
        int numcode = vecCountry.size() + 1;
        country.setValue(numcode, alphaCode,  chiName, engName, teamSize, gold, silver, bronze);
        // 插入到国家表中
        add_country(country);
        QString sql = QString("select medal_db from country where name_en='%1'").arg(chiName);
        QSqlQuery query(sql);
        if (query.next()) {
            QString db = query.value(0).toString();
            database->init(db);
        }
        vecCountry.push_back(country);
        // 更新国家显示
        initData1();
    }
}

void MainWindow::on_pushButton_addAthlete_clicked()
{
    int nRow = ui->tableWidget->currentIndex().row();
    if(nRow < 0)//先选某一行，再插入运动员信息
    {
        QMessageBox::information(nullptr, "提示", "请选择国家后再进行新增运动员信息！");
        return;
    }

    int nRowCount = ui->tableWidget->rowCount();
    if(nRowCount <= 0)
    {
        return;
    }

    addAthlete dlg;
    dlg.setCountryName(m_chiName);
    if(dlg.exec() == QDialog::Accepted)
    {
        QString code = dlg.getCode();
        QString athleteName = dlg.getAthleteName();
        QString medalDate = dlg.getMedalDate();
        QString medalLevel = dlg.getMedalLevel();
        QString eventName = dlg.getEventName();
        QString score = dlg.getScore();
        QString country_name = dlg.getCountry_name();
        int index1 = getCountryIndex(country_name);
        int index2 = getSportIndex(country_name, athleteName);
        if(index2 >= 0)
        {
            QMessageBox::information(nullptr, "提示", QString("[%1]已存在，请勿重复添加！").arg(athleteName));
            return;
        }
        int id =  getSprotsNum() + 1;
        Athlete sport;
        sport.setValue(id, athleteName, code, medalDate, medalLevel, eventName, score, country_name);
        vecCountry[index1].vecAthlete.push_back(sport);
        add_medal(sport);
        //initData2(0, country_name);
    }
}

void MainWindow::on_tableWidget_2_itemClicked(QTableWidgetItem* item)
{
    int nRow = item->row();
    if(nRow < 0)
    {
        return;
    }

    QString athleteName  = ui->tableWidget_2->item(nRow, 1)->text();
    if(athleteName.isEmpty())
    {
        return;
    }

    m_athleteName = athleteName;
}

void MainWindow::on_pushButton_addAthlete_update_clicked()
{
    int nRow = ui->tableWidget_2->currentIndex().row();//选中
    if(nRow < 0)
    {
        QMessageBox::information(nullptr, "提示", "请选择一位运动员后再编辑！");
        return;
    }

    int nRowCount = ui->tableWidget_2->rowCount();
    if(nRowCount <= 0)
    {
        return;
    }

    updateAthlete dlg;
    dlg.setAthleteName(m_athleteName);
    dlg.setCountryName(m_chiName);
    if(dlg.exec() == QDialog::Accepted)
    {
        QString athleteName = dlg.getAthleteName();
        QString code = dlg.getCode();
        QString medalDate = dlg.getMedalDate();
        QString medalLevel = dlg.getMedalLevel();
        QString eventName = dlg.getEventName();
        QString score = dlg.getScore();
        QString country_name = dlg.getCountryName();

        int index1 = getCountryIndex(country_name);
        int index2 = getSportIndex(country_name, athleteName);
        Athlete& sport = vecCountry[index1].vecAthlete[index2];
        int id = sport.getId();
        sport.setValue(id, athleteName, code, medalDate, medalLevel, eventName, score, country_name);
        saveAthlete();
        ui->tableWidget_2->item(nRow, 2)->setText(code);
        ui->tableWidget_2->item(nRow, 3)->setText(medalDate);
        ui->tableWidget_2->item(nRow, 4)->setText(medalLevel);
        ui->tableWidget_2->item(nRow, 5)->setText(eventName);
        ui->tableWidget_2->item(nRow, 6)->setText(score);
    }
}

void MainWindow::on_pushButton_addAthlete_updateCountry_clicked()
{
    int nRow = ui->tableWidget->currentIndex().row();
    if(nRow < 0)
    {
        QMessageBox::information(nullptr, "提示", "请选择国家后再进行编辑操作！");
        return;
    }

    int nRowCount = ui->tableWidget->rowCount();
    if(nRowCount <= 0)
    {
        return;
    }

    updateCountry dlg;
    dlg.setChiName(m_chiName);
    if(dlg.exec() == QDialog::Accepted)
    {
        QString alphaCode = dlg.getAlphaCode();
        QString chiName = dlg.getChiName();
        QString engName = dlg.getEngName();
        int teamSize = dlg.getTeamSize().toInt();
        int gold = dlg.getGold().toInt();
        int silver = dlg.getSilver().toInt();
        int bronze = dlg.getBronze().toInt();

        int index1 = getCountryIndex(chiName);
        Country& country = vecCountry[index1];
        int numCode = country.getNumCode();
        country.setValue(numCode, alphaCode,  chiName, engName, teamSize, gold, silver, bronze);
        saveCountry();

        ui->tableWidget->item(nRow, 1)->setText(dlg.getAlphaCode());
        ui->tableWidget->item(nRow, 3)->setText(dlg.getEngName());
        ui->tableWidget->item(nRow, 4)->setText(dlg.getTeamSize());
        ui->tableWidget->item(nRow, 5)->setText(dlg.getGold());
        ui->tableWidget->item(nRow, 6)->setText(dlg.getSilver());
        ui->tableWidget->item(nRow, 7)->setText(dlg.getBronze());
    }
}


void MainWindow::readCountry()
{
    QFile aFile("data_country.txt");
    if(!aFile.exists()) //文件不存在
    {
        return;
    }
    if(!aFile.open(QIODevice::ReadOnly | QIODevice::Text)) //以文本方式打开
    {
        return;
    }
    QTextStream aStream(&aFile); //用文本流读取文件
    aStream.setLocale(QLocale::system());  //显示汉字
    int number = 0;
    aStream >> number;
    for (int i = 0; i < number; ++i)
    {
        Country country;
        country.read(aStream);
        vecCountry.push_back(country);
    }
    aFile.close();
}

void MainWindow::queryCountry()
{
    QString sql = "select * from country";
    QSqlQuery query;

    query.exec(sql);

    while (query.next()) {
        Country country;

        int num = query.value(0).toInt();
        QString alphaCode = query.value(1).toString();
        QString chiName = query.value(2).toString();
        QString engName = query.value(3).toString();
        int team_size = query.value(4).toInt();
        QString mdb = query.value(5).toString(); 
        int gold, sliver, bronze;

        // TODO medal info 
        gold = 0;
        sliver = 0;
        bronze = 0;
        country.setValue(num, alphaCode,  chiName, engName, team_size, gold, sliver, bronze);
        vecCountry.push_back(country);
    }
}

void MainWindow::saveCountry()
{
    QFile aFile("data_country.txt");
    if(!aFile.open(QIODevice::WriteOnly | QIODevice::Text)) //以文本方式打开
    {
        return;
    }

    QTextStream aStream(&aFile); //用文本流读取文件
    aStream.setLocale(QLocale::system());  //显示汉字
    int number = vecCountry.size();
    aStream << number << "\n";
    for (int i = 0; i < number; ++i)
    {
        vecCountry[i].save(aStream);
    }
    aFile.close();
}

void MainWindow::add_country(Country &country)
{
    int numcode;
    QString alphaCode;
    QString chiName;
    QString engName;
    int teamSize = 0;
    int gold = 0;
    int silver = 0;
    int bronze = 0;
 
    country.getValue(numcode, alphaCode, chiName, engName, teamSize, gold, silver, bronze);
    QString sql = QString("select * from country where name_en='%1'").arg(engName);

    qDebug() << "sql: " + sql;

    QSqlQuery query(sql);
    if (query.next()) {
        QMessageBox::information(nullptr, "提示", QString("[%1]已存在，请勿重复添加！").arg(engName));
    } else {
        QString sql = QString("insert into country values(%1, '%2', '%3', '%4', %5, '%6')")
        .arg(numcode)
        .arg(alphaCode, chiName, engName).arg(teamSize).arg(chiName + "_table");
        QSqlQuery query;
        if (!query.exec(sql)) {
            QMessageBox::information(nullptr, "提示", QString("添加国家入库失败"));
        }
    }
}

void MainWindow::add_medal(Athlete &athlete)
{
    QString athleteName;
    QString code;
    QString medalDate;
    QString medalLevel;
    QString eventName;
    QString score;
    QString country_name;
    int id;

    athlete.getValue(id, athleteName, code, medalDate, medalLevel, eventName, score, country_name);

    QString sql = QString("insert into %1 values(%2, '%3', %4, '%5', %6, '%7', '%8')")
            .arg(id)
            .arg(athleteName)
            .arg(code)
            .arg(eventName)
            .arg(score)
            .arg(medalLevel, medalDate);

    QSqlQuery query;
    if (!query.exec(sql)) {
        QMessageBox::information(nullptr, "提示", QString("添加奖牌入库失败"));
        return;
    }
}

void MainWindow::readAthlete()
{

    QFile aFile("data_sport.txt");
    if(!aFile.exists()) //文件不存在
    {
        return;
    }
    if(!aFile.open(QIODevice::ReadOnly | QIODevice::Text)) //以文本方式打开
    {
        return;
    }

    QTextStream aStream(&aFile); //用文本流读取文件
    aStream.setLocale(QLocale::system());  //显示汉字
    int number = 0;
    aStream >> number;
    for (int i = 0; i < number; ++i)
    {
        Athlete sport;
        sport.read(aStream);
        int index = getCountryIndex(sport.getCountryName());
        if (index >= 0)
        {
            vecCountry[index].vecAthlete.push_back(sport);
        }
    }
    aFile.close();
}

void MainWindow::saveAthlete()
{
    QFile aFile("data_sport.txt");
    if(!aFile.open(QIODevice::WriteOnly | QIODevice::Text)) //以文本方式打开
    {
        return;
    }

    QTextStream aStream(&aFile); //用文本流读取文件
    aStream.setLocale(QLocale::system());  //显示汉字
    int number = getSprotsNum();
    aStream << number << "\n";
    for (int i = 0; i < vecCountry.size(); ++i)
    {
        for (int j = 0; j < vecCountry[i].vecAthlete.size(); ++j)
        {
            vecCountry[i].vecAthlete[j].save(aStream);
        }
    }
    aFile.close();
}

int MainWindow::getSprotsNum()
{
    int size = 0;
    for (int i = 0; i < vecCountry.size(); ++i)
    {
        size += vecCountry[i].vecAthlete.size();
    }
    return size;
}

int MainWindow::getCountryIndex(QString country)
{
    for (int i = 0; i < vecCountry.size(); ++i)
    {
        if (vecCountry[i].getName() == country)
        {
            return i;
        }
    }
    return -1;
}

int MainWindow::getSportIndex(QString country, QString name)
{
    int i = getCountryIndex(country);
    if(i >= 0)
    {
        for(int j = 0; j < vecCountry[i].vecAthlete.size(); j++)
        {
            if( vecCountry[i].vecAthlete[j].getName() == name)
            {
                return j;
            }
        }
    }
    return -1;
}



bool SortFunc(Country& a, Country& b)
{
    int gold_a = 0;
    int silver_a = 0;
    int bronze_a = 0;
    a.getMedals(gold_a, silver_a, bronze_a);


    int gold_b = 0;
    int silver_b = 0;
    int bronze_b = 0;
    b.getMedals(gold_b, silver_b, bronze_b);

    if(gold_a != gold_b)
    {
        return gold_a > gold_b;
    }

    if(silver_a != silver_b)
    {
        return silver_a > silver_b;
    }
    return bronze_a > bronze_b;
}


void MainWindow::on_pushButton_showCountryRank_clicked()
{
    std::sort(vecCountry.begin(), vecCountry.end(), SortFunc);
    initData1();
}




